const bent = require('bent');
import qs = require('querystring');
import { IGlobal } from '../entity/Global';

declare var global: IGlobal;
/**http库 */
export class HttpUtils {
    static async get(url: string, data?: any, responseType: string = "json", headers?: any) {
        if (data) {
            if (url.indexOf("?") == -1) {
                url += "?";
            } else {
                url += "&";
            }
            url += qs.stringify(data);
        }
        let requestFunc = bent("GET", this._getEncoding(responseType));
        try {
            let result = await requestFunc(url, null, headers);
            return result;
        } catch (error) {
            this.logError(url, data, "get", error);
            throw error;
        }
    }

    static async post(url: string, data?: any, responseType: string = "json", headers?: any) {
        let header = { 'content-type': 'application/json' };
        if (headers) {
            Object.assign(header, headers);
        }
        let requestFunc = bent("POST", this._getEncoding(responseType));
        try {
            let result = await requestFunc(url, data, header);
            return result;
        } catch (error) {
            this.logError(url, data, "post", error);
            throw error;
        }
    }

    static getIp(requestMsg: any, isProxy: boolean): string {
        var ip = isProxy ? requestMsg.headers["x-forwarded-for"] : requestMsg.connection.remoteAddress;
        ip = ip.replace("::ffff:", "");
        return ip;
    }

    /**获取本机的ip */
    static getLocalIp() {
        const os = require('os');
        var interfaces = os.networkInterfaces();
        for (var devName in interfaces) {
            var iface = interfaces[devName];
            for (var i = 0; i < iface.length; i++) {
                var alias = iface[i];
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    return alias.address;
                }
            }
        }
    }

    private static _getEncoding(responseType: string) {
        if (responseType == "text" || responseType == "string") {
            return "string";
        } else if (responseType == "buffer") {
            return "buffer";
        } else {
            return "json";
        }
    }

    static logError(url: string, data: any, method: string, error: any, response?: any) {
        if (global.log) {
            if (response) {
                global.log.error("请求拒绝:\nurl=[" + url + "]\ndata=[" + JSON.stringify(data || {}) + "]\nmethod=[" + method + "]\nerror=[" + JSON.stringify(error || {}) + "]\nresponse=[" + JSON.stringify(response || {}) + "]");
            }
            else {
                global.log.error("请求出错:\nurl=[" + url + "]\ndata=[" + JSON.stringify(data || {}) + "]\nmethod=[" + method + "]\nerror=[" + JSON.stringify(error) + "]");
            }
        }
    }
}